package com.medicine.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.medicine.constant.MessageConstant;
import com.medicine.constant.StatusConstant;
import com.medicine.dto.MedicineDTO;
import com.medicine.dto.MedicinePageQueryDTO;
import com.medicine.entity.Medicine;
import com.medicine.entity.Specification;
import com.medicine.entity.GroupMedicine;
import com.medicine.exception.DeletionNotAllowedException;
import com.medicine.exception.MedicineStopFailedException;
import com.medicine.mapper.GroupMedicineMapper;
import com.medicine.mapper.SpecificationMapper;
import com.medicine.mapper.MedicineMapper;
import com.medicine.result.PageResult;
import com.medicine.service.MedicineService;
import com.medicine.vo.MedicineVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MedicineServiceImpl implements MedicineService {

    @Autowired
    private MedicineMapper medicineMapper;

    @Autowired
    private SpecificationMapper specificationMapper;

    @Autowired
    private GroupMedicineMapper groupMedicineMapper;

    /**
     * 新增药品和对应规格数据
      * @param medicineDTO
     */
    @Transactional
    public void saveWithSpecification(MedicineDTO medicineDTO) {

        Medicine medicine = new Medicine();

        BeanUtils.copyProperties(medicineDTO, medicine);

        //向药品表插入一条数据
        medicineMapper.insert(medicine);

        //获取insert语句生成的主键值
        Long medicineId = medicine.getId();

        List<Specification> specifications = medicineDTO.getSpecifications();
        if (specifications != null && specifications.size() > 0) {
            specifications.forEach(dishFlavor -> {
                dishFlavor.setMedicineId(medicineId);
            });
            //向规格表插入多条数据
            specificationMapper.insertBatch(specifications);
        }
    }

    /**
     * 药品分页查询
     * @param medicinePageQueryDTO
     * @return
     */
    public PageResult pageQuery(MedicinePageQueryDTO medicinePageQueryDTO) {

        PageHelper.startPage(medicinePageQueryDTO.getPage(), medicinePageQueryDTO.getPageSize());

        Page<MedicineVO> page = medicineMapper.pageQuery(medicinePageQueryDTO);

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 药品批量删除
     *
     * @param ids
     */
    @Transactional//事务
    public void deleteBatch(List<Long> ids) {
        //判断当前药品是否能够删除---是否存在起售中的药品？？
        for (Long id : ids) {
            Medicine medicine = medicineMapper.getById(id);
            if (medicine.getStatus() == StatusConstant.ENABLE) {
                //当前药品处于起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.MEDICINE_ON_SALE);
            }
        }

        //判断当前药品是否能够删除---是否被药组关联了？？
        List<Long> groupIds = groupMedicineMapper.getGroupIdsByMedicineIds(ids);
        if (groupIds != null && groupIds.size() > 0) {
            //当前药品被药组关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.MEDICINE_BE_RELATED_BY_GROUP);
        }

        //TODO 批量删除优化改造
        //删除药组表中的药品数据
        for (Long id : ids) {
            medicineMapper.deleteById(id);
            //删除药品关联的规格数据
            specificationMapper.deleteByMedicineId(id);
        }
    }

    /**
     * 根据id查询药品和对应的规格数据
     *
     * @param id
     * @return
     */
    public MedicineVO getByIdWithSpecification(Long id) {
        //根据id查询药品数据
        Medicine medicine = medicineMapper.getById(id);

        //根据药品id查询规格数据
        List<Specification> specifications = specificationMapper.getByMedicineId(id);//后绪步骤实现

        //将查询到的数据封装到VO
        MedicineVO medicineVO = new MedicineVO();
        BeanUtils.copyProperties(medicine, medicineVO);
        medicineVO.setSpecifications(specifications);

        return medicineVO;
    }

    /**
     * 根据id修改药品基本信息和对应的规格信息
     *
     * @param medicineDTO
     */
    public void updateWithSpecification(MedicineDTO medicineDTO) {
        Medicine medicine = new Medicine();
        BeanUtils.copyProperties(medicineDTO, medicine);

        //修改药品表基本信息
        medicineMapper.update(medicine);

        //删除原有的规格数据
        specificationMapper.deleteByMedicineId(medicineDTO.getId());

        //重新插入规格数据
        List<Specification> specifications = medicineDTO.getSpecifications();
        if (specifications != null && specifications.size() > 0) {
            specifications.forEach(Specification -> {
                Specification.setMedicineId(medicineDTO.getId());
            });
            //向规格表插入n条数据
            specificationMapper.insertBatch(specifications);
        }
    }

    /**
     * 根据分类id查询药品
     * @param categoryId
     * @return
     */
    public List<Medicine> list(Long categoryId) {
        Medicine medicine = Medicine.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return medicineMapper.list(medicine);
    }

    /**
     * 药品的起售停售
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //被药组关联的药品不能被停售---通过药品id查group_medicine表
        GroupMedicine groupMedicine = groupMedicineMapper.getGroupMedicineByMedicineId(id);

        if(groupMedicine != null){
            //药品被药组关联，不能被停售
            throw new MedicineStopFailedException(MessageConstant.MEDICINE_BE_STOPED_BY_GROUP);
        }

        Medicine medicine = Medicine.builder()
                .id(id)
                .status(status)
                .build();

        medicineMapper.update(medicine);
    }

    /**
     * 条件查询药品和规格
     * @param medicine
     * @return
     */
    public List<MedicineVO> listWithSpecification(Medicine medicine) {
        List<Medicine> medicineList = medicineMapper.list(medicine);

        List<MedicineVO> medicineVOList = new ArrayList<>();

        for (Medicine d : medicineList) {
            MedicineVO medicineVO = new MedicineVO();
            BeanUtils.copyProperties(d,medicineVO);

            //根据药品id查询对应的规格
            List<Specification> specifications = specificationMapper.getByMedicineId(d.getId());

            medicineVO.setSpecifications(specifications);
            medicineVOList.add(medicineVO);
        }

        return medicineVOList;
    }
}
